<script lang="ts" setup>
import { watch, reactive } from 'vue';
import { SYS_USER_QUERY_APP, OPEN_SYS_USER_QUERY_APP } from '/@/api/modules/base/app-sys-user';
import { AppUserListPopupState } from './index.d';

const props = withDefaults(
  defineProps<{
    modelValue: boolean;
    /**
     * 标题
     */
    title?: string;
    /**
     * 用户所在部门id
     */
    organId?: string;
    /**
     * 用户所在部门
     */
    organ?: AppCascaderOrganDto;
    /**
     * 是否开放接口
     */
    isOpen?: boolean;
  }>(),
  {
    modelValue: false,
    title: '用户',
    isOpen: false,
  },
);
const emits = defineEmits<{
  (e: 'update:modelValue'): void;
  (e: 'onSelected', user: AppSysUser.Dto, organ: AppCascaderOrganDto): void;
}>();

const state = reactive<AppUserListPopupState>({
  organCascaderVisible: false,
  activeOrganIds: [],
  activeOrgans: [],
  activePage: 1,
  loading: false,
  finished: false,
  name: '',
  list: [],
});

/**
 * @description 列表查询
 * @param page -当前页
 * @param pageSize -每页条数
 * @param name
 */
function queryList(
  page: number = 1,
  pageSize: number = 15,
  organId: string[] = [],
  name: string = '',
) {
  if (!page && state.finished) return;
  state.loading = true;

  function handleRes(res: AppSysUserApi.SysUserQueryAppResp) {
    state.loading = false;

    if (
      state.activePage >=
      (res.comQuery?.pageCount ||
        (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
        1)
    )
      state.finished = true;
    if (!res.content || !res.content.length) return;

    res.content.forEach((item) => state.list.push(item));

    state.activePage += 1;
  }

  if (props.isOpen) {
    OPEN_SYS_USER_QUERY_APP({
      comQuery: { page, pageSize },
      organId,
      name,
    })
      .then((res) => {
        handleRes(res);
      })
      .catch(() => {
        state.loading = false;
      });
  } else {
    SYS_USER_QUERY_APP({
      comQuery: { page, pageSize },
      organId,
      name,
    })
      .then((res) => {
        handleRes(res);
      })
      .catch(() => {
        state.loading = false;
      });
  }
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;

  queryList(state.activePage, 15, state.activeOrganIds, state.name);
}

watch(props, (newProps) => {
  if (!newProps.modelValue) return;

  state.organCascaderVisible = false;
  state.activeOrganIds = newProps.organId ? [newProps.organId] : [];
  state.activeOrgans = newProps.organ ? [newProps.organ] : [];
  state.activePage = 1;
  state.finished = false;
  state.loading = false;
  state.name = '';
  state.list = [];

  //默认显示所有用户
  onLoading();
});
</script>

<template>
  <teleport to="body">
    <nut-popup
      :visible="props.modelValue"
      position="bottom"
      closeable
      round
      :style="{ height: '90vh' }"
      @click-close-icon="emits('update:modelValue')"
      @click-overlay="emits('update:modelValue')"
    >
      <view class="app-user-list-popup app-popup--2">
        <view class="app-user-list-popup__header app-popup__header">{{ props.title }}</view>
        <nut-cell
          title="所在部门"
          class="app-user-list-popup__organs-cell"
          :desc="
            state.activeOrgans
              .map((o) => {
                return o.text;
              })
              .toString()
              .replace(/,/g, ' > ') || '请选择所在部门'
          "
          @click="
            () => {
              if (props.organId) return;

              state.organCascaderVisible = !state.organCascaderVisible;
            }
          "
        />
        <nut-searchbar
          v-model="state.name"
          placeholder="请输入人员姓名"
          @change="
            () => {
              state.activePage = 1;
              state.finished = false;
              state.loading = false;
              state.list = [];
              onLoading();
            }
          "
        >
        </nut-searchbar>
        <scroll-view
          class="app-popup__wrapper"
          :scroll-y="true"
          :lower-threshold="100"
          @scrolltolower="onLoading()"
        >
          <view class="app-user-list-popup__wrapper">
            <view
              v-for="item in state.list"
              :key="item.id"
              class="app-user-item"
              @click="
                () => {
                  emits(
                    'onSelected',
                    item,
                    state.activeOrgans.filter((o) => {
                      return o.value === state.activeOrganIds[0];
                    })[0],
                  );
                  emits('update:modelValue');
                }
              "
            >
              <view class="app-user-item--left">{{ item.name || item.nickName }}</view>
              <view class="app-user-item--right">选择</view>
            </view>
          </view>

          <view class="app-popup__list-tips">
            <text v-if="!state.list.length">暂无数据！</text>
            <text v-else-if="state.list.length && state.loading">加载中...</text>
            <text v-else-if="state.list.length && state.finished">加载完成!</text>
          </view>
        </scroll-view>
      </view>

      <app-organ-cascader
        title="部门"
        v-model="state.organCascaderVisible"
        :is-open="props.isOpen"
        @on-selected="(organIds: string[], organs: AppCascaderOrganDto[]) => {
        state.activePage = 1;
        state.finished = false;
        state.loading = false;
        state.list = [];
        state.activeOrgans = organs;
        state.activeOrganIds = [organIds[organIds.length - 1]];
        onLoading();
      }"
      />
    </nut-popup>
  </teleport>
</template>

<style lang="scss">
@import './index.scss';
</style>
